#!/bin/bash

# 开发环境启动脚本
# 基于奥卡姆剃刀原则：一键启动完整开发环境

set -e

echo "🚀 启动 Weubi Crawler 开发环境..."

# 检查基础设施是否运行
check_infrastructure() {
    echo "🔍 检查基础设施状态..."
    
    if ! docker-compose ps | grep -q "postgres.*Up"; then
        echo "📦 启动 PostgreSQL..."
        docker-compose up -d postgres
        sleep 5
    fi
    
    if ! docker-compose ps | grep -q "redis.*Up"; then
        echo "📦 启动 Redis..."
        docker-compose up -d redis
        sleep 3
    fi
    
    if ! docker-compose ps | grep -q "rabbitmq.*Up"; then
        echo "📦 启动 RabbitMQ..."
        docker-compose up -d rabbitmq
        sleep 5
    fi
    
    echo "✅ 基础设施检查完成"
}

# 启动开发服务
start_dev_services() {
    echo "🔧 启动开发服务..."
    
    # 在后台启动 turbo dev
    pnpm dev &
    DEV_PID=$!
    
    echo "✅ 开发服务已启动 (PID: $DEV_PID)"
    echo ""
    echo "📋 服务地址："
    echo "  - Web界面: http://localhost:3000"
    echo "  - API服务: http://localhost:3001"
    echo "  - RabbitMQ管理: http://localhost:15672"
    echo ""
    echo "💡 按 Ctrl+C 停止所有服务"
    
    # 等待用户中断
    trap 'echo "🛑 停止开发服务..."; kill $DEV_PID 2>/dev/null || true; exit 0' INT
    wait $DEV_PID
}

# 主函数
main() {
    check_infrastructure
    start_dev_services
}

main
